package com.zl.easybuy.util;

import com.zl.easybuy.pojo.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SessionUtil {
    private final static String USER_IN_SESSION="loginUser";
    private final static String CART_IN_SESSION="cart";
    //获取session
    public static HttpSession getSession(){
        return ((ServletRequestAttributes)(RequestContextHolder.getRequestAttributes())).getRequest().getSession();
    }
    //存储用户信息
    public static void setLoginSession(User user){
        if(user!=null){
            getSession().setAttribute(USER_IN_SESSION,user);
        }
    }
    //存储购物车信息
    public static void setCartInSession(ShoppingCart shoppingCart){
        if(shoppingCart!=null){
            getSession().setAttribute(CART_IN_SESSION,shoppingCart);
        }
    }
    //清空购物车
    public static void clearCart(){
        getSession().removeAttribute(CART_IN_SESSION);
    }
    //获取当前购物车
    public static ShoppingCart getCurrentCart(){
        return (ShoppingCart)getSession().getAttribute(CART_IN_SESSION);
    }
    //获取当前用户
    public static User getCurrentUser(){
       return (User) getSession().getAttribute(USER_IN_SESSION);
    }
    //清除用户信息
    public static void invalidUserSession(){
        getSession().invalidate();
    }
}
